const BaseController = require("./base/base");
const Result = require("../utils/result");
const { get_client_ip } = require("../utils/tools");
const jwt = require("jsonwebtoken");
const UsersModel = require("../model/users");
const LogsModel = require("../model/logs");
var svgCaptcha = require('svg-captcha');
const { getTokenUser, isAdmin } = require("../middlewares/auth");
class UsersController extends BaseController {
  constructor() {
    super();
    this.key = "guoyei";
  }
  login(req, res, next) {
    setTimeout(async () => {
      try {
        const { username, password } = req.body;
        if (!username || !password) return res.json(Result.fail("用户名或密码错误"));
        let userinfo = await UsersModel.findOne({ username, password });
        if (!userinfo) return res.json(Result.fail("用户名或密码错误"));
        if (!userinfo.state) return res.json(Result.fail("用户已禁用"));
        new LogsModel({ username, ip: get_client_ip(req) }).save();
        const authorization = jwt.sign({ _id: userinfo._id, username, head: userinfo.head }, this.key, { expiresIn: "1d" });
        res.json(Result.ok("success", { _id: userinfo._id, username, head: userinfo.head, authorization }));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  verify(req, res, next) {
    setTimeout(async () => {
      try {
        const { authorization } = req.headers; //headers 里面的所有key都会是小写
        if (!authorization) return res.json(Result.fail("authorization错误"));
        const data = jwt.verify(authorization, this.key); //{"user_name":"admin","iat":1635349069,"exp":1635435469}
        res.json(Result.ok("success", data));
      } catch (err) {
        //篡改{"name":"JsonWebTokenError","message":"invalid token"}
        //过期{"name":"TokenExpiredError","message":"jwt expired","expiredAt":"2021-10-28T03:28:45.000Z"}
        res.json(Result.fail(err));
      }
    })
  }
  captcha(req, res, next) {
    setTimeout(async () => {
      const { width = "120", height = "40" } = req.query;
      var codeConfig = { size: 4, ignoreChars: 'abh0QOoqg9l1iv', noise: 2, color: true, };
      if (width) codeConfig["width"] = width;
      if (height) codeConfig["height"] = height;
      var captcha = svgCaptcha.create(codeConfig);
      req.session.captcha = captcha.text.toLowerCase();
      res.set('Content-Type', 'image/svg+xml');
      res.send(captcha.data);
    })
  }
  vcaptcha(req, res, next) {
    setTimeout(async () => {
      try {
        let { vcode } = req.params;
        let { captcha } = req.session;
        if (!vcode || !captcha) return res.json(Result.fail("没有验证码"));
        captcha = captcha.toLowerCase();
        vcode = vcode.toLowerCase();
        if (vcode != captcha) return res.json(Result.fail("验证码错误"));
        res.json(Result.ok());
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  getData(req, res, next) {
    setTimeout(async () => {
      let data = await UsersModel.aggregate([{ $group: { _id: '$role', name: { $first: '$role' }, value: { $sum: 1 } } }])
      res.json(Result.ok("success", data))
      // res.json(Result.ok("success", [
      //   { value: 10, name: '管理员' },
      //   { value: 20, name: '用户' },
      // ]))
    })
  }
  findUsersByPage(req, res, next) {
    setTimeout(async () => {
      try {
        let { username = '', realname = '', tel = '', email = '', role = '' } = req.query;
        let username_filter = {}
        let realname_filter = {}
        let tel_filter = {}
        let email_filter = {}
        let role_filter = {}
        if (username) username_filter = { username: { $regex: username, $options: '$i' } }
        if (realname) realname_filter = { realname: { $regex: realname, $options: '$i' } }
        if (tel) tel_filter = { tel: { $regex: tel, $options: '$i' } }
        if (email) email_filter = { email: { $regex: email, $options: '$i' } }
        if (role) role_filter = { role }

        let _filter = Object.assign(username_filter, realname_filter, tel_filter, email_filter, role_filter);
        let { page = 1, pagesize = 1 } = req.query
        page *= 1;
        pagesize *= 1;
        let total = await UsersModel.countDocuments(_filter)
        let list = await UsersModel.find(_filter, { password: 0 }).skip((page - 1) * pagesize).limit(pagesize).sort({ '_id': -1 }).exec()
        res.json(Result.ok("success", { total, list }));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  addUser(req, res, next) {
    setTimeout(async () => {
      try {
        let { username } = req.body;
        if (await UsersModel.findOne({ username })) return res.json(Result.fail("用户已存在"));
        let user = await new UsersModel({ ...req.body }).save();
        res.json(!user ? Result.fail("添加失败") : Result.ok("添加成功"));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  findOneById(req, res, next) {
    setTimeout(async () => {
      try {
        let { id } = req.params;
        let user = await UsersModel.findById({ _id: id })
        res.json(!user ? Result.fail("fail") : Result.ok("success", user));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  updateOneById(req, res, next) {
    setTimeout(async () => {
      try {
        //{"acknowledged":true,"matchedCount":1,"upsertedId":null,"upsertedCount":0,"matchedCount":1}
        let ret = await UsersModel.updateOne({ _id: req.params.id }, req.body)
        res.json(!ret.matchedCount ? Result.fail("修改失败") : Result.ok("修改成功"));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  deleteOneById(req, res, next) {
    setTimeout(async () => {
      try {
        //{ deletedCount: 1 }
        let ret = await UsersModel.deleteOne({ _id: req.params.id })
        res.json(!ret.deletedCount ? Result.fail("删除失败") : Result.ok("删除成功"))
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  editpwd(req, res, next) {
    setTimeout(async () => {
      try {
        const { _id, username } = getTokenUser(req);
        const { oldpwd = '', password = '' } = req.body;
        if (!oldpwd || !password) return res.json(Result.fail("oldpwd 和 password 不能为空"))
        let user = await UsersModel.findById({ _id })
        if (!user) return res.json(Result.fail("用户不存在"))
        if (oldpwd != user.password) return res.json(Result.fail("原密码错误"))
        let ret = await UsersModel.updateOne({ _id }, { password })
        res.json(!ret.matchedCount ? Result.fail("修改失败") : Result.ok("修改成功"))
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  findLogsByPage(req, res, next) {
    setTimeout(async () => {
      try {
        let { username = '' } = req.query;
        let _filter = {}
        if (username) _filter = { username: { $regex: username, $options: '$i' } }
        let { page = 1, pagesize = 1 } = req.query
        page *= 1;
        pagesize *= 1;
        let total = await LogsModel.countDocuments(_filter)
        let list = await LogsModel.find(_filter).skip((page - 1) * pagesize).limit(pagesize).sort({ '_id': -1 }).exec()
        res.json(Result.ok("success", { total, list }));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
}
module.exports = new UsersController().resolve();